package pe.edutec.app.layer.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pe.edutec.app.domain.Alumno;
import pe.edutec.app.layer.service.AlumnoService;


@WebServlet({ "/BuscarAlumnos","/NuevoAlumno", "/EditarAlumno", "/EliminarAlumno", "/GrabarAlumno" })
public class AlumnoController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String alias = request.getServletPath();
		if(alias.equals("/BuscarAlumnos")){
			buscarAlumnos(request,response);
		} else if(alias.equals("/NuevoAlumno")){
			nuevoAlumno(request,response);
		} else if(alias.equals("/EditarAlumno")){
			editarAlumno(request,response);
		} else if(alias.equals("/GrabarAlumno")){
			grabarAlumno(request,response);
		}
	}

	private void grabarAlumno(HttpServletRequest request,
			HttpServletResponse response) {
		// TODO Auto-generated method stub
		
	}

	private void editarAlumno(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String id = request.getParameter("id");
		AlumnoService service= new AlumnoService();
		Alumno a = service.buscarPorId(id);
		
		request.setAttribute("accion", "EDITAR");
		request.setAttribute("alumno", a);
		RequestDispatcher rd = request.getRequestDispatcher("editarAlumno.jsp");
		rd.forward(request, response);
	}

	private void nuevoAlumno(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("accion", "NUEVO");
		RequestDispatcher rd = request.getRequestDispatcher("editarAlumno.jsp");
		rd.forward(request, response);
	}

	private void buscarAlumnos(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String destino;
		try {
			String apellido = request.getParameter("apellido");
			AlumnoService service = new AlumnoService();
			List<Alumno> lista = service.buscarPorApellido(apellido);
			request.setAttribute("lista", lista);
			if(lista.isEmpty()){
				request.setAttribute("mensaje", "Tabla esta vacia.");
			}
			destino = "listadoAlumnos.jsp";
		} catch (Exception e) {
			request.setAttribute("error", e.getMessage());
			destino = "error.jsp";
		}
		RequestDispatcher rd = request.getRequestDispatcher(destino);
		rd.forward(request, response);
	}

}
